package com.linwen.excise.leetcode;

/**
 * @ClassName _1572矩阵对角线元素的和
 * @Description TODO
 * @Author zero
 * @DATE 2024/10/7 1:59 PM
 * @Version 1.0
 */
public class _1572矩阵对角线元素的和 {
    public static void main(String[] args) {
        _1572矩阵对角线元素的和 inst = new _1572矩阵对角线元素的和();
        int[][] mat = {{1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}};
        System.out.println(inst.diagonalSum(mat));
        System.out.println(inst.diagonalSum2(mat));
    }

    public int diagonalSum(int[][] mat) {
        int res = 0;
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat.length; j++) {
                if (i == j || i + j == mat.length - 1) {
                    res += mat[i][j];
                }
            }
        }
        return res;
    }

    public int diagonalSum2(int[][] mat) {
        int res = 0;
        int n = mat.length;
        // 偶数
        if ((n & 1) == 0) {
            for (int i = 0; i < n; i++) {
                res += mat[i][i] + mat[n - i - 1][i];
            }
        } else {
            for (int i = 0; i < n; i++) {
                res += mat[i][i] + mat[n - i - 1][i];
            }
            res -= mat[n / 2][n / 2];
        }
        return res;
    }
}
